package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.EditPassword;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import com.itheima.utils.POIUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    //获取当前登录（认证）用户的用户名
    @RequestMapping("/getLoginUsername")
    public Result getLoginUsername() {
        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            String password = user.getPassword();
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    @RequestMapping("/findPage")//分页查询
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return userService.findPage(queryPageBean);
    }


    @RequestMapping("/add")//添加用户
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result add(@RequestBody com.itheima.pojo.User user,Integer[] roleIds) {
        try {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode("1234");
            user.setPassword(password);
            userService.add(user,roleIds);
            return new Result(true, "添加用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加失败");
        }
    }

    @RequestMapping("/edit")//修改用户
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result edit(@RequestBody com.itheima.pojo.User user , Integer[] roleIds) {
        try {
            userService.edit(user,roleIds);
            return new Result(true, "编辑用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑失败");
        }

    }

    @RequestMapping("/delete")//删除用户
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delete(Integer id) {
        try {
            userService.deleteById(id);
            return new Result(true, "删除用户成功");
        } catch (Exception e) {
            String mes = e.getMessage();
            e.printStackTrace();
            return new Result(false, mes);
        }

    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            com.itheima.pojo.User user = userService.findById(id);
            return new Result(true, "查询角色管理信息成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }

    }

    @RequestMapping("/findRoleNameByUserId")
    public  Result findUserIdsByRoleId(Integer userId){
        try {
            /*List<Role> list = userService.findRoleNameByUserId(userId);*/
            List<Integer> list = userService.findRoleIdsNameByUserId(userId);

            return  new Result(true,"查询用户管理成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败");
        }

    }

    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<Role> list=userService.findAll();
            return new Result(true,"查询用户成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败");
        }
    }

    //文件上传（Excel）
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);
            List<com.itheima.pojo.User> data = new ArrayList<>();
            if (list != null && list.size() > 0) {
                for (String[] strings : list) {
                    String birthday = strings[0];
                    String gender = strings[1];
                    String username = strings[2];
                    String telephone = strings[3];
                    com.itheima.pojo.User users = new com.itheima.pojo.User();
                    users.setBirthday(new SimpleDateFormat("yyyy/MM/dd").parse(birthday));
                    users.setGender(gender);
                    users.setUsername(username);
                    users.setTelephone(telephone);
                    data.add(users);
                }
            }
            userService.addData(data);
            return new Result(true, "导入数据成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "导入失败");
        }

    }

    @RequestMapping("/findByCondition")
    public Result findByCondition(String username){
        try {
            com.itheima.pojo.User user = userService.findAllByUsername(username);
            return  new Result(true,"查询角色管理信息成功",user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败");
        }
    }

    @RequestMapping("/editUser")//修改用户
    public Result editUser(@RequestBody com.itheima.pojo.User user) {
        try {
            userService.editUser(user);
            return new Result(true, "编辑用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑失败");
        }

    }

    @RequestMapping("/editPass")//修改密码
    public Result editPass(@RequestBody EditPassword password) {
        if(!userService.confirm(password)){
            return new Result(false, "旧密码校验错误");
        }
        try {
            userService.editPassword(password);
            return new Result(true, "修改密码成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改密码失败");
        }
    }

}
